package cn.edu.nju.ws.aquila.database;
import java.beans.PropertyVetoException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

import com.mchange.v2.c3p0.ComboPooledDataSource;


public  class DBConnectionFactory {
	private DBConnectionFactory(){
		//Nothing
	}
	private static ComboPooledDataSource datasource = null;
	private static void initDataSource(){
		try {
			Properties properties = new Properties();
			properties.load(DBConnectionFactory.class.getClassLoader().getResourceAsStream("conf.properties"));
			datasource = new ComboPooledDataSource();
			datasource.setDriverClass("com.mysql.jdbc.Driver");
			datasource.setJdbcUrl(properties
					.getProperty("db_connection_url"));
			datasource.setUser(properties
					.getProperty("db_connection_user"));
			datasource.setPassword(properties
					.getProperty("db_connection_password"));
			datasource.setMaxPoolSize(20);
			datasource.setMinPoolSize(10);
			datasource.setIdleConnectionTestPeriod(600);
			properties.clear();
			properties = null;
		} catch (PropertyVetoException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public  synchronized  static Connection getConnection(){
		Connection con= null;
		try {
			if(datasource==null)
				initDataSource();
			con = datasource.getConnection();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return con;
	}
	
	public static synchronized void finalized(){
		if(datasource!=null){
			datasource.close();
			datasource = null;
		}
	}
}
